var fs = require('fs'),
  crypto = require('crypto');

var os = require('os');
if (os.platform() == 'win32') {
  var chilkat = require('chilkat_node6_win32');
} else if (os.platform() == 'linux') {
  if (os.arch() == 'arm') {
    var chilkat = require('chilkat_node6_arm');
  } else if (os.arch() == 'x86') {
    var chilkat = require('chilkat_node6_linux32');
  } else {
    var chilkat = require('chilkat_node6_linux64');
  }
} else if (os.platform() == 'darwin') {
  var chilkat = require('chilkat_node6_macosx');
}

var _merPublicKeyId = '';
var _priKeyPath = '';
var _pubKeyPath = '';

/**
 * 验证签名
 * @param {[string]}  src_sign   [签名源串]
 * @param {[string]}  signature  [已生成的签名串]
 * @param {[string]}  public_key [公钥地址]
 * @returns {[boolean]}          [成功或者失败]
 */
function verify(src_sign, signature) {
  var public_key = fs.readFileSync(_pubKeyPath);
  var verifier = crypto.createVerify('RSA-SHA1');
  verifier.update(new Buffer(src_sign, 'utf-8'));
  return verifier.verify(public_key, signature, 'base64');
}

/**
 * 签名
 * @param  {[string]} src_sign   [签名源串]
 * @param  {[string]} priKeyPath [私钥地址]
 * @return {[string]}            [已生成的签名串]
 */
function sign(src_sign) {
  var private_key = '';
  try {
    private_key = fs.readFileSync(_priKeyPath);
  } catch (e) {
    console.error(e);
  }
  var signer = crypto.createSign('RSA-SHA1');
  signer.update(src_sign);
  return signer.sign(private_key, 'base64');
}

/**
 * 初始化私钥和公钥
 * @param  {[string]} priKeyPath [私钥地址]
 * @param  {[string]} pubKeyPath [公钥地址]
 */
function init(priKeyPath, pubKeyPath) {
  var cert = new chilkat.Cert();
  var success;
  success = cert.LoadFromFile(pubKeyPath);
  if (success !== true) {
    console.log(cert.LastErrorText);
    return;
  }
  _merPublicKeyId = cert.SerialNumber;
  _priKeyPath = priKeyPath;
  _pubKeyPath = pubKeyPath;
}

/**
 * 获取证序列号
 * @return {[string]} [公钥序列号]
 */
function getSignCertId() {
  return _merPublicKeyId;
}

exports.verify = verify;
exports.sign = sign;
exports.getSignCertId = getSignCertId;
exports.init = init;
